import MySQLdb,json
from datetime import datetime
import time

# ne=[]
# conn=MySQLdb.connect(host="172.16.100.31",user="root",passwd="admin",db="rainbow_3_0")
# cursor=conn.cursor()
# cursor.execute("SELECT * FROM ne where neid not in(select neid from rcpe) order by ne_neid,neid")
# [ne.append((x[0],x[1])) for x in cursor.fetchall()]
# cursor.close()
# conn.close()

nd=[]
allrp=[]
rp=[]

conn=MySQLdb.connect(host="172.16.100.31",user="root",passwd="admin",db="rainbow_3_0")
cursor=conn.cursor()
cursor.execute("SELECT neid,dsCfgNwIpAddr FROM rnd")
[nd.append((x[0],x[1])) for x in cursor.fetchall()]
cursor.execute("select neid,ne_neid from ne where neid in (select neid from rrp)")
[allrp.append((x[0],x[1])) for x in cursor.fetchall()]
cursor.execute("select ne.neid,ne_neid,embedaddress,nename from rembed,ne where rembed.neid in (select neid from rrp where rpcfgnwhop=1 or rpcfgnwhop=3 or rpcfgnwhop=5) and rembed.neid=ne.neid")
[rp.append((x[0],x[1],x[2],x[3])) for x in cursor.fetchall()]

cursor.close()
conn.close()


# print rp


# ne=[(1,None),(2,1),(3,1),(6,5),(5,None),(9,2)]
# tree=[(2,1),(3,1),(6,5),(9,1)]
# print json.dumps(tree)
tree=[]

def getParentId(id):
  for x in allrp:
    if x[0]==id:
      return x[1]
      
def getRootId(id):
  root=pid=id
  while pid<>None:
    pid=getParentId(pid)
    if pid<>None:
      root=pid
  return root

def getNdIp(id):
  for x in nd:
    if x[0]==id:
      return x[1]
s=time.time()      
for x in rp:
  rpid=x[0]
  rootid=getRootId(x[1])
  oid=x[2]
  rpmac=x[3]
  ndip=getNdIp(rootid)
  tree.append((rpid,rootid,ndip,oid,rpmac))
 
e=time.time()
print tree
print len(tree)
print e-s


    